package com.zhijian.medical.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.zhijian.medical.dao.local.DigitalSliceCaseFileMapper;
import com.zhijian.medical.entity.UploadParam;
import com.zhijian.medical.entity.po.DigitalSliceCaseFile;
import com.zhijian.medical.entity.vo.request.DigitalSliceCaseFileCuttingInfoSearchVo;
import com.zhijian.medical.entity.vo.request.DigitalSliceCaseFileSaveOrUpdateVo;
import com.zhijian.medical.entity.vo.request.DigitalSliceCaseFileSearchVo;
import com.zhijian.medical.entity.vo.response.DigitalSliceCaseFileCuttingInfoVo;
import com.zhijian.medical.entity.vo.response.DigitalSliceCaseFileVo;
import com.zhijian.medical.service.DigitalSliceCaseFileCuttingInfoService;
import com.zhijian.medical.service.DigitalSliceCaseFileService;
import com.zhijian.medical.util.Page;
import gov.nist.isg.archiver.DirectoryArchiver;
import gov.nist.isg.archiver.FilesArchiver;
import gov.nist.isg.pyramidio.BufferedImageReader;
import gov.nist.isg.pyramidio.PartialImageReader;
import gov.nist.isg.pyramidio.ScalablePyramidBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 数字切片-文件相关业务处理层
 *
 * @author HCG
 * @version: 1.0
 * @date 2022-12-30 21:42:12
 */
@Slf4j
@Service
public class DigitalSliceCaseFileServiceImpl implements DigitalSliceCaseFileService {

    @Autowired
    private DigitalSliceCaseFileMapper mapper;

    @Autowired
    private DigitalSliceCaseFileCuttingInfoService digitalSliceCaseFileCuttingInfoService;

    @Autowired
    private UploadParam uploadParam;

    @Override
    public DigitalSliceCaseFile selectById(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public DigitalSliceCaseFileVo selectVoById(Long id) {
        return mapper.selectVoById(id);
    }

    @Override
    public void deleteById(Long id) {
        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public Long insert(DigitalSliceCaseFile digitalSliceCaseFile) {
        Date now = new Date();
        digitalSliceCaseFile.setCreateTime(now);
        digitalSliceCaseFile.setUpdateTime(now);
        return mapper.insert(digitalSliceCaseFile) > 0 ? digitalSliceCaseFile.getId() : 0L;
    }

    @Override
    public boolean saveOrUpdate(DigitalSliceCaseFile digitalSliceCaseFile) {
        if (Objects.isNull(digitalSliceCaseFile.getId())) {
            return insert(digitalSliceCaseFile) != 0;
        } else {
            return this.updateByPrimaryKeySelective(DigitalSliceCaseFile.builder()
                    .id(digitalSliceCaseFile.getId())
                    .name(digitalSliceCaseFile.getName())
                    .filePath(digitalSliceCaseFile.getFilePath())
                    .build());
        }
    }

    @Transactional(rollbackFor = Exception.class, value = "localTransactionManager")
    @Override
    public boolean saveOrUpdate(DigitalSliceCaseFileSaveOrUpdateVo digitalSliceCaseFileSaveOrUpdateVo) {
        //图片真实路径
        String realPath = digitalSliceCaseFileSaveOrUpdateVo.getRealPath();
        //生成个文件夹名称
        String f = String.format("%s%s", DateUtil.format(new Date(), "yyyyMMdd"), RandomUtil.randomString(6));
        //整的文件夹
        File folderFile = new File(String.format("%s%s", uploadParam.getStorePath(), f));
        File realFile = new File(realPath);
        BufferedImage image = null;
        try {
            image = ImageIO.read(realFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        boolean mkdirs = folderFile.mkdirs();
        ScalablePyramidBuilder spb = new ScalablePyramidBuilder();
        FilesArchiver archiver = null;
        try {
            archiver = new DirectoryArchiver(folderFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        PartialImageReader pir = new BufferedImageReader(image);
        try {
            spb.buildPyramid(pir, "test", archiver, 1);
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (Objects.isNull(digitalSliceCaseFileSaveOrUpdateVo.getId())) {
            return insert(digitalSliceCaseFileSaveOrUpdateVo) != 0;
        } else {
            return this.updateByPrimaryKeySelective(DigitalSliceCaseFile.builder()
                    .id(digitalSliceCaseFileSaveOrUpdateVo.getId())
                    .name(digitalSliceCaseFileSaveOrUpdateVo.getName())
                    .filePath(digitalSliceCaseFileSaveOrUpdateVo.getFilePath())
                    .build());
        }
    }

    @Override
    public boolean update(DigitalSliceCaseFile digitalSliceCaseFile) {
        Date now = new Date();
        digitalSliceCaseFile.setUpdateTime(now);
        return mapper.updateByPrimaryKey(digitalSliceCaseFile) != 0;
    }

    @Override
    public boolean updateByPrimaryKeySelective(DigitalSliceCaseFile record) {
        Date now = new Date();
        record.setUpdateTime(now);
        return mapper.updateByPrimaryKeySelective(record) != 0;
    }

    @Override
    public Integer count(DigitalSliceCaseFileSearchVo digitalSliceCaseFileSearchVo) {
        return mapper.count(digitalSliceCaseFileSearchVo);
    }

    @Override
    public List<DigitalSliceCaseFileVo> selectList(DigitalSliceCaseFileSearchVo digitalSliceCaseFileSearchVo) {
        return mapper.selectList(digitalSliceCaseFileSearchVo);
    }

    @Override
    public Page<DigitalSliceCaseFileVo> selectPage(DigitalSliceCaseFileSearchVo digitalSliceCaseFileSearchVo) {
        //先直接查总数
        int count = count(digitalSliceCaseFileSearchVo);
        //分页
        Page<DigitalSliceCaseFileVo> page = new Page<>(true, count, digitalSliceCaseFileSearchVo.getPageNum(), digitalSliceCaseFileSearchVo.getPageSize());
        digitalSliceCaseFileSearchVo.setStartIndex(page.getStartIndex());
        page.setPage(true);
        page.setTotalCount(count);
        List<DigitalSliceCaseFileVo> responseVos = this.selectList(digitalSliceCaseFileSearchVo);
        page.setData(responseVos);
        return page;
    }

    @Override
    public boolean insertBatch(List<DigitalSliceCaseFile> entities) {
        return CollectionUtil.isNotEmpty(entities) && mapper.insertBatch(entities) > 0;
    }

    @Override
    public List<DigitalSliceCaseFileVo> selectByTypeAndCaseId(String type, Long caseId) {
        List<DigitalSliceCaseFileVo> digitalSliceCaseFileVos = this.selectList(DigitalSliceCaseFileSearchVo.builder()
                .type(type)
                .caseId(caseId)
                .build());
        if (CollectionUtil.isEmpty(digitalSliceCaseFileVos)) {
            return Collections.emptyList();
        }
        digitalSliceCaseFileVos.forEach(digitalSliceCaseFileVo -> {
            //把切割后的图片信息赋值进去
            List<DigitalSliceCaseFileCuttingInfoVo> digitalSliceCaseFileCuttingInfoVos = digitalSliceCaseFileCuttingInfoService.selectList(DigitalSliceCaseFileCuttingInfoSearchVo.builder()
                    .fileId(digitalSliceCaseFileVo.getId())
                    .build());
            digitalSliceCaseFileVo.setFileCuttingInfo(CollectionUtil.isEmpty(digitalSliceCaseFileCuttingInfoVos) ? null : digitalSliceCaseFileCuttingInfoVos.get(0));
        });
        return digitalSliceCaseFileVos;
    }

    @Override
    public DigitalSliceCaseFileVo selectByTypeAndCaseIdAndName(String type, Long caseId, String name) {
        List<DigitalSliceCaseFileVo> digitalSliceCaseFileVos = this.selectList(DigitalSliceCaseFileSearchVo.builder()
                .type(type)
                .caseId(caseId)
                .name(name)
                .build());
        if (CollectionUtil.isNotEmpty(digitalSliceCaseFileVos)) {
            return digitalSliceCaseFileVos.get(0);
        }
        return null;
    }

}